//
//  EventViewController.m
//  lvtu
//
//  Created by Apple on 12-4-4.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "EventViewController.h"
#import "TripInfo.h"
#import "EventViewCell.h"
#import "EventDetailViewController.h"

@implementation EventViewController
@synthesize isDelStyle;
@synthesize elementType;
@synthesize delegate;
@synthesize reloading=_reloading;
@synthesize refreshHeaderView;
@synthesize m_ShowAry;
@synthesize cellstatusDict;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (id)initWithType:(BOOL)Style edit:(BOOL)isEdit
{
    self = [super init];
    if (self) {
        // Custom initialization
        isDelStyle = Style;
        isTripEdit = isEdit;
        
        m_ShowAry = [[NSMutableArray alloc] init];
        cellstatusDict = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)dealloc
{
    [cellstatusDict removeAllObjects];
    [cellstatusDict release];cellstatusDict = nil;
    [m_ShowAry removeAllObjects];
    [m_ShowAry release]; m_ShowAry = nil; 
    [super dealloc];
}
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.title = @"添加事件";
    UILabel* tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    [tempLabel setText:@"添加事件"];
    [tempLabel setBackgroundColor:[UIColor clearColor]];
    [tempLabel setTextAlignment:UITextAlignmentCenter];
    [tempLabel setTextColor:[UIColor colorWithRed:111/255.0 green:117/255.0 blue:81/255.0 alpha:1.0]];
    [tempLabel setFont:[UIFont boldSystemFontOfSize:20]];
    self.navigationItem.titleView = tempLabel;
    [tempLabel release];
    tempLabel = nil;
    
    UIImage* backImage = [UIImage imageNamed:@"btn_back_normal.png"];
    UIButton* leftbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftbutton.frame = CGRectMake(0, 0, backImage.size.width, backImage.size.height);
    [leftbutton setBackgroundImage:backImage forState:UIControlStateNormal];
    [leftbutton setBackgroundImage:[UIImage imageNamed:@"btn_back_press.png"] forState:UIControlStateHighlighted];
    [leftbutton addTarget:self action:@selector(findOutButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* findoutButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftbutton];
    //signupButton.image = [UIImage imageNamed:@"btn_finish_normal.png"];
    self.navigationItem.leftBarButtonItem = findoutButtonItem;
    [findoutButtonItem release];
    
    searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, 15, 293, 50)];
    searchTextField.backgroundColor = [UIColor colorWithRed:227/255.0 green:227/255.0 blue:227/255.0 alpha:1.0];
    searchTextField.background = [UIImage imageNamed:@"bg_imput.png"];
    searchTextField.font = [UIFont systemFontOfSize:18];
    searchTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;                
    [searchTextField setAutocorrectionType:UITextAutocorrectionTypeNo];
    [searchTextField setDelegate:self];
    [searchTextField setReturnKeyType:UIReturnKeyGo];
    [searchTextField setClipsToBounds:YES];
    [searchTextField setClearsOnBeginEditing:YES];
    
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
	button.frame = CGRectMake(250, 10, 35, 35);
    [button setBackgroundImage:[UIImage imageNamed:@"btn_search2_normal.png"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"btn_search2_press.png"] forState:UIControlStateHighlighted];
	[button addTarget:self action:@selector(searchButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[searchTextField addSubview:button];
    
    if (!isDelStyle) {
        [self.view addSubview:searchTextField];
        
        NSDictionary* info;
//        if (isTripEdit == YES) {
//            info= [[NSDictionary alloc] initWithObjectsAndKeys:[[DataSource shareInstance] getCityIdEdit] ,@"c_city_id",[NSString stringWithFormat:@"%d",elementType],@"element_type",nil];
//        }
//        else {
//            info= [[NSDictionary alloc] initWithObjectsAndKeys:[[DataSource shareInstance] getCityId] ,@"c_city_id",[NSString stringWithFormat:@"%d",elementType],@"element_type",nil];
//        }
        info= [[NSDictionary alloc] initWithObjectsAndKeys:[[DataSource shareInstance] getDefaultCityId] ,@"c_city_id",[NSString stringWithFormat:@"%d",elementType],@"element_type",nil];
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = ELEMENTSEARCH;
        msg.ui_delegate = self;
        
        [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_element_search" postInfo:info userInfo:msg];
        baseAlert = [[UIAlertView alloc] initWithTitle:@"正在加载..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [baseAlert show];
        
        UIActivityIndicatorView* aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        aiv.center = CGPointMake(baseAlert.bounds.size.width/2.0f, baseAlert.bounds.size.height-40.0f);
        [aiv startAnimating];
        [baseAlert addSubview:aiv];
        [aiv release];
    }
    else
    {
        [searchTextField release];
    }
    
    if (isDelStyle) {
        if (self.view.frame.size.height > 480)
        {
            m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(15, 15, 290, 450) style:UITableViewStylePlain];
        }
        else
        {
            m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(15, 15, 290, 370) style:UITableViewStylePlain];
        }
        [self.view addSubview:m_tableView];
    }
    else
    {
        if (self.view.frame.size.height > 480)
        {
            m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(15, 70, 290, 380) style:UITableViewStylePlain];
        }
        else
        {
            m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(15, 70, 290, 300) style:UITableViewStylePlain];
        }
        if (refreshHeaderView == nil) {
            refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - m_tableView.bounds.size.height, 320.0f, m_tableView.bounds.size.height)];
            refreshHeaderView.backgroundColor = [UIColor colorWithRed:231.0/255.0 green:235.0/255.0 blue:212.0/255.0 alpha:1.0];
            refreshHeaderView.bottomBorderThickness = 1.0;
            [m_tableView addSubview:refreshHeaderView];
            m_tableView.showsVerticalScrollIndicator = YES;
            [refreshHeaderView release];
        }
        
        //创建页脚button
        footSpinnerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 288, 40)];
        UIButton* footButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [footButton setBackgroundColor:[UIColor colorWithRed:231.0/255.0 green:235.0/255.0 blue:212.0/255.0 alpha:1.0]];
        [footButton setFrame:CGRectMake(0, 0, 288, 40)];
        [footButton setTitle:@"更多"forState:UIControlStateNormal];
        [footButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [footButton addTarget:self action:@selector(footButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
        [footButton addTarget:self action:@selector(footButtonTouchDown:) forControlEvents:UIControlEventTouchDown];
        [footSpinnerView addSubview:footButton];
        m_tableView.tableFooterView = footSpinnerView;
    }
    m_tableView.delegate = self;
    m_tableView.dataSource = self;
    //[self.view addSubview:m_tableView];
    
    UIImageView* inputView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, m_tableView.backgroundView.frame.size.width, m_tableView.backgroundView.frame.size.height)];
    UIImage* stretchImg = [[UIImage imageNamed:@"bg_whiteframe.png"] stretchableImageWithLeftCapWidth:30 topCapHeight:20];
    inputView.image = stretchImg;  
    inputView.clipsToBounds = YES;
    inputView.userInteractionEnabled = YES;
    [m_tableView.backgroundView addSubview:inputView];
    
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self selector:@selector(cellClick:)
               name:@"cellclick"
             object:nil];
    
    NSNotificationCenter *nc1 = [NSNotificationCenter defaultCenter];
    [nc1 addObserver:self selector:@selector(celldelClick:)
               name:@"celldelclick"
             object:nil];
    
    nodataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    nodataLabel.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2-50);
    nodataLabel.text = @"无数据";
    nodataLabel.backgroundColor = [UIColor clearColor];
    nodataLabel.hidden = YES;
    [self.view addSubview:nodataLabel];
    
    isRefresh = NO;
    pageNum = 1;
    [m_tableView reloadData];
}

- (void)viewDidUnload
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"cellclick" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"celldelclick" object:nil];
    [baseAlert release];
    [footSpinnerView release];
    [nodataLabel release]; nodataLabel = nil;
    [m_tableView release]; m_tableView = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return NO;
}

- (void)cellClick:(NSNotification*)note
{
    PlaceInfo* info = [note.userInfo objectForKey:@"info"];
    if ([delegate addEvent:info type:elementType]) {
        [cellstatusDict setObject:@"1" forKey:info.shopid];
    }
    else
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经添加过啦~" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 2001;
        [alert show];
        [alert release];
    }
}

- (void)celldelClick:(NSNotification*)note
{
    PlaceInfo* info = [note.userInfo objectForKey:@"info"];
    if ([delegate delEvent:info type:elementType]) {
        if (!isDelStyle) {
            return;
        }
        if ([[m_ShowAry objectAtIndex:0] isKindOfClass:[NSDictionary class]]) {
            for (NSDictionary* dict in m_ShowAry) {
                if ([[dict objectForKey:@"c_shop_id"] isEqualToString:info.shopid]) {
                    [m_ShowAry removeObject:dict];
                    [m_tableView reloadData];
                    break;
                }
            }
        }
        else {
            [m_ShowAry removeObject:info];
            [m_tableView reloadData];
        }
    }
}

- (void)findOutButtonPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchButtonPressed:(id)sender
{
    isRefresh = YES;
    NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:searchTextField.text,@"keyword",[[DataSource shareInstance] getDefaultCityId] ,@"c_city_id",[NSString stringWithFormat:@"%d",elementType],@"element_type",nil];
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = ELEMENTSEARCH;
    msg.ui_delegate = self;
    
    [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_element_search" postInfo:info userInfo:msg];
    [baseAlert show];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [m_ShowAry count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"StatusCell";
    
    EventViewCell *cell = (EventViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[EventViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    if (isDelStyle) {
        [cell setButtonType:1];
    }
    else
    {
        [cell setButtonType:0];
    }
    BOOL isSelect = NO;
    id tempinfo = [m_ShowAry objectAtIndex:indexPath.row];
    if ([tempinfo isKindOfClass:[PlaceInfo class]]) {
        if ([cellstatusDict objectForKey:((PlaceInfo*)tempinfo).shopid])
        {
            isSelect = YES;
        }
    }
    else {
        if ([cellstatusDict objectForKey:[((NSDictionary*)tempinfo) objectForKey:@"c_shop_id"]]) 
        {
            isSelect = YES;
        }
    }  
    
    [cell setInfo:[m_ShowAry objectAtIndex:indexPath.row] status:isSelect];
    // Configure the cell...
    //    [cell setVideoCell:[m_ShowAry objectAtIndex:indexPath.row]:self.tableView];
    //    cell.cellProfilePic.delegate = self;
    //    [cell.cellProfilePic setM_row:indexPath.row];
    //    cell.cellContentPic.delegate = self;
    //    [cell.cellContentPic setM_row:indexPath.row];
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    //[tableView deselectRowAtIndexPath:indexPath animated:YES];
    //EventViewCell *cell = (EventViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    //[cell selectButtonPressed];
    if (!isDelStyle) {
        PlaceInfo* pageInfo = [m_ShowAry objectAtIndex:indexPath.row];
        EventDetailViewController * eventDetailViewController = [[EventDetailViewController alloc] initWithPlaceInfo:pageInfo];
        NSArray* currentArray = [[DataSource shareInstance] getCurrentEvent];
        for (PlaceInfo* place in currentArray) {
            if ([pageInfo.shopid isEqualToString:place.shopid]) {
                eventDetailViewController.isTripExistEvent = YES;
            }
        }
        eventDetailViewController.delegate = self.delegate;
        [self.navigationController pushViewController:eventDetailViewController animated:YES];
        [eventDetailViewController release];
    }
    NSLog(@"index = %d",indexPath.row);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    //    self.tableView.delegate = nil;
    //    StatusCell *cell = (StatusCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    //    self.tableView.delegate = self;
    //    return cell.cellHeight;
    return 80;
}

#pragma -mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == searchTextField)
    {
        [searchTextField setText:@""];
        [searchTextField setTextColor:[UIColor blackColor]];
    }
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [searchTextField resignFirstResponder];
    if ( textField == searchTextField && [searchTextField.text isEqualToString:@""])
    {
        [searchTextField setPlaceholder:@""];
        [searchTextField setTextColor:[UIColor grayColor]];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (1 == range.length) {//按下回格键
        return YES;
    }
    
    if ([string isEqualToString:@"\n"])
    {//按下return键
        //这里隐藏键盘，不做任何处理
        [textField resignFirstResponder];
        return NO;
    }
    else
    {
        return YES;
    }
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == searchTextField)
    {
        [searchTextField setText:@""];
        [searchTextField setPlaceholder:@""];
        [searchTextField setTextColor:[UIColor grayColor]];
    }
    return YES;
}
#pragma mark - buttonaction

//button点下改变背景色的效果
-(void)footButtonTouchDown:(id)button;
{
    [button setBackgroundColor:[UIColor blueColor]];
}

//处理button抬起消息
- (void)footButtonTouchUpInside:(id)button
{
    [button setBackgroundColor:[UIColor clearColor]];
    
    //从数据库中每次多获取最新的20条微博,放入model后加入数组
    //    NSArray* ary = [[NSArray alloc] initWithArray:[database getStatusesData:[m_ShowArycount]+20]];
    //[m_ShowAry removeAllObjects];
    //    for (int i = 0; i < [ary count]; i++) {
    //        NSDictionary* dict =  [databasegetUserData:[[ary objectAtIndex:i] objectForKey:@"user"]];
    //        StatusInfo* statusInfo = [[StatusInfoalloc] initWithDictionary:[ary objectAtIndex:i] :dict];
    //        [m_ShowAryaddObject:statusInfo];
    //        [statusInfo release];
    //    }
    //    [ary release];
    
    //刷新界面，判断是否显示foot
    //    [self.tableViewreloadData];
    //    if ([databasegetStatusCount] <= [m_ShowArycount]) {
    //        self.tableView.tableFooterView.hidden = YES;
    //    }
    NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:[[DataSource shareInstance] getDefaultCityId] ,@"c_city_id",[NSString stringWithFormat:@"%d",elementType],@"element_type",[NSString stringWithFormat:@"%d",pageNum+1],@"page",nil];
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = ELEMENTSEARCH;
    msg.ui_delegate = self;
    
    [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_element_search" postInfo:info userInfo:msg];
    [baseAlert show];
}
#pragma mark - ScrollView callbacks
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{	
	if (scrollView.isDragging) {
		if (refreshHeaderView.state == EGOOPullRefreshPulling && scrollView.contentOffset.y > -65.0f && scrollView.contentOffset.y < 0.0f && !_reloading) {
			[refreshHeaderView setState:EGOOPullRefreshNormal];
		} else if (refreshHeaderView.state == EGOOPullRefreshNormal && scrollView.contentOffset.y < -65.0f && !_reloading) {
			[refreshHeaderView setState:EGOOPullRefreshPulling];
		}
	}
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{	
    NSLog(@"Scroll view offset: %f", scrollView.contentOffset.y);
    
	if (scrollView.contentOffset.y <= - 65.0f && !_reloading) {
		_reloading = YES;
		[refreshHeaderView setState:EGOOPullRefreshLoading];
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.2];
		m_tableView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
		[UIView commitAnimations];
        [self reloadTableViewDataSource];
	}
}

#pragma mark - RefreshHeaderView methods
- (void)dataSourceDidFinishLoadingNewData:(NSNumber *)loadedData
{	
	_reloading = NO;
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:.3];
	[m_tableView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
	[UIView commitAnimations];
	
	[refreshHeaderView setState:EGOOPullRefreshNormal];
    
}

- (void)reloadTableViewDataSource
{
    if (isDelStyle) {
        [self dataSourceDidFinishLoadingNewData:nil];
        return;
    }
	NSLog(@"Please override reloadTableViewDataSource.");
    isRefresh = YES;
    NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:[[DataSource shareInstance] getDefaultCityId] ,@"c_city_id",[NSString stringWithFormat:@"%d",elementType],@"element_type",nil];
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = ELEMENTSEARCH;
    msg.ui_delegate = self;
    
    [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_element_search" postInfo:info userInfo:msg];
    [baseAlert show];
}

- (void)dataSourceDidFailPresentingError
{
    NSLog(@"Please implement your own UIAlert view.");
}

#pragma -mark DataSourceDelegate

- (void)onDataSourceSucCallback:(CoreMsg *)coreMsg withData:(id)data
{
    if (isRefresh == YES) {
        [m_ShowAry removeAllObjects];
        isRefresh = NO;
    }
    [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
    if ([coreMsg.data isEqual: ELEMENTSEARCH]) {
        nodataLabel.hidden = YES;
        ElementPageInfo* pageInfo = (ElementPageInfo*)data;
        pageNum = pageInfo.currentPageId;
        if (pageInfo.totlePageCount && pageInfo.totlePageCount > 1) {
            m_tableView.tableFooterView = footSpinnerView;
        }
        else {
            m_tableView.tableFooterView = nil;
        }
        for (int i = 0 ; i < [pageInfo.elementArray count]; i++) {
            [m_ShowAry addObject:[pageInfo.elementArray objectAtIndex:i]];
        }
        if (![m_tableView isDescendantOfView:self.view]) {
            [self.view addSubview:m_tableView];
        }
        [m_tableView reloadData];
        [self dataSourceDidFinishLoadingNewData:nil];
    }
}

- (void)onDataSourceFailCallback:(CoreMsg *)coreMsg withData:(id)data
{
    [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
    if ([coreMsg.data isEqual: ELEMENTSEARCH]) {
        nodataLabel.hidden = NO;
        m_tableView.tableFooterView = nil;
//        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:data delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        alert.tag = 2001;
//        [alert show];
//        [alert release];
        [self dataSourceDidFinishLoadingNewData:nil];
    }
}
@end
